import java.math.BigInteger;
import java.security.*;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.KeyAgreement;
import javax.crypto.SecretKey;
import javax.crypto.spec.*;

/**
 * Diffie Hellman Bitches
 * @author Zohaib
 *
 */
public class DiffieHellman
{
	PrivateKey privateKey;
	BigInteger[] GeneratePG()
	{
		BigInteger[] ret = new BigInteger[2];
		int bitLength = 512; // 512 bits
	    SecureRandom rnd = new SecureRandom();
	    ret[0] = BigInteger.probablePrime(bitLength, rnd);
	    ret[1] = BigInteger.probablePrime(bitLength, rnd);
		return ret;
	}
	
	byte[] CreateSendInteger(BigInteger p, BigInteger g, int key)
	{
		try {
		    // Use the values to generate a key pair
		    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DH");
		    DHParameterSpec dhSpec = new DHParameterSpec(p, g, key);
		    keyGen.initialize(dhSpec);
		    KeyPair keypair = keyGen.generateKeyPair();

		    // Get the generated public and private keys
		    privateKey = keypair.getPrivate();
		    PublicKey publicKey = keypair.getPublic();

		    // Send the public key bytes to the other party...
		    return publicKey.getEncoded();
		} catch (java.security.InvalidAlgorithmParameterException e) {
		} catch (java.security.NoSuchAlgorithmException e) {
		}
		return null;
	}
	
	SecretKey CreateFullKey(byte[] publicKeyBytes)
	{
		try {
		    // Retrieve the public key bytes of the other party

		    // Convert the public key bytes into a PublicKey object
		    X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(publicKeyBytes);
		    KeyFactory keyFact = KeyFactory.getInstance("DH");
		    PublicKey publicKey = keyFact.generatePublic(x509KeySpec);

		    // Prepare to generate the secret key with the private key and public key of the other party
		    KeyAgreement ka = KeyAgreement.getInstance("DH");
		    ka.init(privateKey);
		    ka.doPhase(publicKey, true);

		    // Specify the type of key to generate;
		    // see Listing All Available Symmetric Key Generators
		    String algorithm = "DES";

		    // Generate the secret key
		    return ka.generateSecret(algorithm);

		    // Use the secret key to encrypt/decrypt data;
		    // see Encrypting a String with DES
		} catch (java.security.InvalidKeyException e) {
		} catch (java.security.spec.InvalidKeySpecException e) {
		} catch (java.security.NoSuchAlgorithmException e) {
		}
		return null;
		
	}
	
}